package com.webdemo07.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webdemo07.pojo.User;
import com.webdemo07.service.impl.UserServiceImpl;
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserServiceImpl userService;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String flag = request.getParameter("flag");
		if("addUser".equals(flag)){
			User user = new User();
			user.setId(Integer.parseInt(request.getParameter("id")));
			user.setName(request.getParameter("name"));
			userService.addUser(user);
			response.sendRedirect(request.getSession().getServletContext().getContextPath()+"/UserServlet?flag=queryUser");
		}else if("queryUser".equals(flag)){
			List<User> users = userService.queryUser();
			request.setAttribute("users", users);
			request.getRequestDispatcher("/WEB-INF/jsp/show.jsp").forward(request, response);
		}else if("deleteUser".equals(flag)){
			int id = Integer.parseInt(request.getParameter("id"));
			userService.deleteUser(id);
			response.sendRedirect(request.getSession().getServletContext().getContextPath()+"/UserServlet?flag=queryUser");
		}else if("updateUser".equals(flag)){
			int id = Integer.parseInt(request.getParameter("id"));
			String name = request.getParameter("name");
			User user = new User();
			user.setId(id);
			user.setName(name);
			userService.updateUser(user);
			response.sendRedirect(request.getSession().getServletContext().getContextPath()+"/UserServlet?flag=queryUser");
		}else if("updateUi".equals(flag)){
			int id = Integer.parseInt(request.getParameter("id"));
			User user = userService.getUser(id);
			request.setAttribute("user", user);
			request.getRequestDispatcher("/WEB-INF/jsp/update.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("/WEB-INF/jsp/add.jsp").forward(request, response);
		}
	}
	public UserServiceImpl getUserService() {
		return userService;
	}
	public void setUserService(UserServiceImpl userService) {
		this.userService = userService;
	}
}
